package com.sun.webmanage.service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.sun.commons.pojo.EasyUIDataGrid;
import com.sun.commons.pojo.SolrInsertData;
import com.sun.commons.utils.ActionUtils;
import com.sun.commons.utils.HttpClientUtil;
import com.sun.commons.utils.IDUtils;
import com.sun.commons.utils.JsonUtils;
import com.sun.dubbo.webmanage.service.TbItemCatDubboService;
import com.sun.dubbo.webmanage.service.TbItemDescDubboService;
import com.sun.dubbo.webmanage.service.TbItemDubboService;
import com.sun.dubbo.webmanage.service.TbItemParamItemDubboService;
import com.sun.exception.DaoException;
import com.sun.redis.dao.RedisDao;
import com.sun.webmanage.model.TbItem;
import com.sun.webmanage.model.TbItemCat;
import com.sun.webmanage.model.TbItemDesc;
import com.sun.webmanage.model.TbItemParamItem;

@Service("TbItemService")
public class TbItemServiceImpl implements TbItemService{

	@Reference
	private TbItemDubboService tbItemDubboService;
	@Reference
	private TbItemCatDubboService tbItemCatDubboService;
	@Reference
	private TbItemDescDubboService tbItemDescDubboService;
	@Reference
	private TbItemParamItemDubboService tbItemParamItemDubboService;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(TbItemService.class);
	
	@Value("${search.host}")
	private String searchUrl;
	@Value("${item.cache.item}")
	private String itemKey;
	@Value("${item.cache.item.desc}")
	private String itemDescKey;
	@Value("${item.cache.item.param}")
	private String itemParamKey;
	
	@Resource
	private RedisDao redisDao;

	@Override
	public EasyUIDataGrid listTbItemPage(int page, int rows,String sort,String order) {
		EasyUIDataGrid listdata = tbItemDubboService.listTbItem(page, rows,sort,order);
		return listdata;
	}

	@Override
	public boolean editStatusTbItem(String ids, String status) throws DaoException {
		final String[] id_array = ids.split(",");
		if(status.equals("1")){//上架
		//启用多线程完成同步工作
		new Thread(){
			public void run() {
				for(String id:id_array){
					//同步solr缓存
					TbItem tbItem = tbItemDubboService.selectTbItemByPK(Long.parseLong(id));
					TbItemDesc tbItemDesc = tbItemDescDubboService.selectTbItemDescByItemId(tbItem.getId());
					TbItemCat itemCat = tbItemCatDubboService.loadTbItemCatByPK(tbItem.getCid());
					SolrInsertData solrInsetData = new SolrInsertData();
					solrInsetData.setId(tbItem.getId());
					solrInsetData.setItem_title(tbItem.getTitle());
					solrInsetData.setItem_sell_point(tbItem.getSellPoint());
					solrInsetData.setItem_price(tbItem.getPrice());
					solrInsetData.setItem_image(tbItem.getImage());
					solrInsetData.setItem_desc(tbItemDesc.getItemDesc());
					solrInsetData.setItem_category_name(itemCat.getName());
					String jsonStr = JsonUtils.objectToJson(solrInsetData);
					LOGGER.info("数据同步===jsonStr:"+jsonStr);
					String doPostJson = HttpClientUtil.doPostJson(searchUrl+"/search/add",jsonStr);
					LOGGER.info("数据同步===doPostJson:"+doPostJson);
					
					//同步redis缓存
					if(!redisDao.exists(itemKey+id)){
						redisDao.setKey(itemKey+id, JsonUtils.objectToJson(tbItem));
					}
					if(!redisDao.exists(itemDescKey+id)){
						redisDao.setKey(itemDescKey+id, JsonUtils.objectToJson(tbItemDesc));
					}
					if(!redisDao.exists(itemParamKey+id)){
						TbItemParamItem tbItemParamItem = tbItemParamItemDubboService.selectTbItemParamItemByItemId(Long.parseLong(id));
						if(tbItemParamItem!=null){
						redisDao.setKey(itemParamKey+id, JsonUtils.objectToJson(tbItemParamItem));
						}
					}
					LOGGER.info("数据同步redis===add:itemid::"+id);
				
				}
			};
			
		}.start();
		
		}else{//下架或删除
			//启用多线程完成同步工作
			new Thread(){
				public void run() {
					List<String> idList = Arrays.asList(id_array);
					String jsonStr = JsonUtils.objectToJson(idList);
					LOGGER.info("数据同步===jsonStr:"+jsonStr);
					String doPostJson = HttpClientUtil.doPostJson(searchUrl+"/search/del",jsonStr);
					LOGGER.info("数据同步===doPostJson:"+doPostJson);
					
					//同步redis缓存
					for (String string : id_array) {
						redisDao.del(itemKey+string);
						redisDao.del(itemDescKey+string);
						redisDao.del(itemParamKey+string);
					}
					LOGGER.info("数据同步redis===del:idList:"+idList);
				};
			}.start();
			
		}
		
		return tbItemDubboService.updateStatusTbItem(ids,Byte.parseByte(status));
	}

	@Override
	public Map<String, Object> saveTbItemRelatoinInfo(TbItem tbItem, String desc,String itemParams) throws DaoException {
		TbItemDesc	tbItemDesc = new TbItemDesc();
		tbItemDesc.setItemDesc(desc);
		TbItemParamItem tbItemParamItem = new TbItemParamItem();
		tbItemParamItem.setParamData(itemParams);
		
		Date now = new Date();
		long itemId = IDUtils.getItemId();
		//商品信息
		tbItem.setId(itemId);//
		tbItem.setCreated(now);//创建时间
		tbItem.setUpdated(now);
		tbItem.setStatus((byte)2);//默认状态下架
		//商品描述信息
		tbItemDesc.setItemId(itemId);//商品id
		tbItemDesc.setCreated(now);//创建时间
		tbItemDesc.setUpdated(now);
		//商品规格信息	
		tbItemParamItem.setItemId(itemId);
		tbItemParamItem.setCreated(now);
		tbItemParamItem.setUpdated(now);
		boolean addTbItemAndDesc = tbItemDubboService.insertTbItemAndDesc(tbItem, tbItemDesc,tbItemParamItem);
		if(addTbItemAndDesc){
			return ActionUtils.ajaxSuccess("商品信息添加成功", "");
		}
		return ActionUtils.ajaxFail("商品信息添加失败", "");
	}

	@Override
	public TbItemDesc loadTbItemDescByItemId(long item_id) {
		return tbItemDescDubboService.selectTbItemDescByItemId(item_id);
	}

	@Override
	public TbItemParamItem loadTbItemParamItemByItemId(long item_id) {
		return tbItemParamItemDubboService.selectTbItemParamItemByItemId(item_id);
	}

	@Override
	public Map<String, Object> updateTbItemRelationInfo(final TbItem tbItem, String desc, String itemParams,
			Long itemParamId) {
		
		Date now = new Date();
		tbItem.setUpdated(now);
		
		final TbItemDesc tbItemDesc = new TbItemDesc();
		tbItemDesc.setItemId(tbItem.getId());
		tbItemDesc.setItemDesc(desc);
		tbItemDesc.setUpdated(now);
		
		final TbItemParamItem tbItemParamItem = new TbItemParamItem();
		tbItemParamItem.setId(itemParamId);
		tbItemParamItem.setParamData(itemParams);
		tbItemParamItem.setUpdated(now);
		
		if(tbItemDubboService.updateItemRelationInfo(tbItem, tbItemDesc, tbItemParamItem)){
			
			//启用多线程完成同步工作
			new Thread(){
				public void run() {
					TbItem selectTbItemByPK = tbItemDubboService.selectTbItemByPK(tbItem.getId());
					TbItemCat itemCat = tbItemCatDubboService.loadTbItemCatByPK(tbItem.getCid());
					SolrInsertData solrInsetData = new SolrInsertData();
					solrInsetData.setId(selectTbItemByPK.getId());
					solrInsetData.setItem_title(selectTbItemByPK.getTitle());
					solrInsetData.setItem_sell_point(selectTbItemByPK.getSellPoint());
					solrInsetData.setItem_price(selectTbItemByPK.getPrice());
					solrInsetData.setItem_image(selectTbItemByPK.getImage());
					solrInsetData.setItem_desc(tbItemDesc.getItemDesc());
					solrInsetData.setItem_category_name(itemCat.getName());
					String jsonStr = JsonUtils.objectToJson(solrInsetData);
					LOGGER.info("数据同步===jsonStr:"+jsonStr);
					String doPostJson = HttpClientUtil.doPostJson(searchUrl+"/search/update",jsonStr);
					LOGGER.info("数据同步===doPostJson:"+doPostJson);
					
					if(selectTbItemByPK.getStatus().equals((byte)1)){
					String id = selectTbItemByPK.getId().toString();
					//同步redis缓存
					redisDao.setKey(itemKey+id, JsonUtils.objectToJson(selectTbItemByPK));
					redisDao.setKey(itemDescKey+id, JsonUtils.objectToJson(tbItemDesc));
					if(tbItemParamItem!=null){
					redisDao.setKey(itemParamKey+id, JsonUtils.objectToJson(tbItemParamItem));
					}
					LOGGER.info("数据同步redis===update:itemid:"+id);
					}
				};
				
			}.start();
			
			return ActionUtils.ajaxSuccess("更新成功", "");
		}
		
		return ActionUtils.ajaxFail("更新失败", "");
	}
	
}
